$(document).ready(function(){

	String.prototype.trim=function(){return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');};
	
	var establishments = [],
		employees = [],
		tins = [],
		empIDs = [];
	
	$( ".datePurchase" ).datepicker();
	
	$.ajax({
		 url: 'ajax.jspx',
		 type: "post",
	     data: 'action=fetchEstablishments',
	     success: function(data) {
	    	establishments = data;
	    	for (var i = 0; i < establishments.length; i++) {
				tins.push(establishments[i].taxIDNumber);
			}
			
			$('#tin').autocomplete({
				source: tins
			});
	     }
	});
	
	$.ajax({
		url: 'ajax.jspx',
		type: 'post',
		data: 'action=fetchEmployees',
		success: function(data) {
			employees = data;
			for (var i = 0; i < employees.lenght; i++) {
				empIDs.push(employees[i].employeeID);
			}
			
			$('#employeeID').autocomplete({
				source: empIDs
			});
		}
	});
	
	$(document).on("click", ":button", function(){
    	var buttonId = $(this).attr('class');
		var listsize = $("#receiptList li").size();
		
		if(buttonId == "removeReceipt" && listsize >= 2){
			//console.log("REMOVE!");
			var parent = $(this).parent().parent().parent();
			parent.remove();
		} else if (buttonId == "removeReceipt" && listsize == 1){
			//console.log("CANNOT REMOVE!");
			alert("ERROR: Cannot remove receipt details. List must not be empty.");
		} else if (buttonId == "addReceipt"){
			//console.log("ADD!");
			var listHtml =  $('.listTemplate').html();
	  		$("#receiptList").append("<li>" + listHtml + "</li>");
	  		$('.datePurchase').datepicker();
		} else if (buttonId == "saveReceipt"){
			//console.log("SAVE!");
			validateEmployeeInput();
			validateEstablishmentInput($(this));
		} else if (buttonId == "exporttocsv"){
			exportToCSV();
		}
	});
	
	$(document).on("blur", ".grossPurchase", function(){
		var grossPurchase = $(this).val();
		var parent = $(this).parent().parent();
		if (grossPurchase > 0){
			var vat = grossPurchase/9.333333;
			var net = grossPurchase - vat;
			parent.find(".vat").val(vat.toFixed(2));
			parent.find(".netPurchase").val(net.toFixed(2));
		}
	});
	function validateEmployeeInput(){
		var errormsg = "";
		var empname = $(".employeeID").val();
		var fname = $(".fname").val();
		var lname = $(".lname").val();
		
		if (empname.trim() === ''){
			errormsg = "Please enter employee number.";
			displayEmployeeError(errormsg);
		} else if (fname.trim() === ''){
			errormsg = "Please enter employee's first name.";
			displayEmployeeError(errormsg);
		} else if (lname.trim() === ''){
			errormsg = "Please enter employee's last name.";
			displayEmployeeError(errormsg);
		} else {
			displayEmployeeError("");
		}
	}
	
	function validateEstablishmentInput(button){
		var errormsg = "";
		var parent = button.parent().parent();
		var name = parent.find(".supplier").val();
		var tin = parent.find(".tin").val();
		var address = parent.find(".address").val();
		var municipality = parent.find(".municipality").val();
		
		var datePurchase = parent.find(".datePurchase").val();
		var grossPurchase = parent.find(".grossPurchase").val();
		
		var tinregex = /(\d{3}-){3}\d{3}/;
		var grossregex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
		
		if (name.trim() === ''){
			errormsg = "Please enter supplier's registered name.";
			displayError(errormsg);
		} else if (tin.trim() === ''){
			errormsg = "Please enter Tax Indentification Number (TIN) of establishment.";
			displayError(errormsg);
		} else if (!tinregex.test(tin)){
			errormsg = "Please enter a valid Tax Indentification Number (TIN). (xxx-xxx-xxx-xxx where x is a number)";
			displayError(errormsg);
		} else if (address.trim() === ''){
			errormsg = "Please enter address of establishment.";
			displayError(errormsg);
		} else if (municipality.trim() === ''){
			errormsg = "Please enter municipality of establishment.";
			displayError(errormsg);
		} else if (datePurchase.trim() === ''){
			errormsg = "Please enter date of purchase.";
			displayError(errormsg);
		} else if (grossPurchase.trim() === ''){
			errormsg = "Please enter total amount of purchase.";
			displayError(errormsg);
		} else if (!grossregex.test(grossPurchase)){
			errormsg = "Total amount of purchase must be a number.";
			displayError(errormsg);
		} else if (grossPurchase <= 0){
			errormsg = "Total amount of purchase must be greater than 0.";
			displayError(errormsg);
		} else {
			displayError("");
			saveEstablishment(button);
			saveReceipt(button);
		}
	}
	
	function displayEmployeeError(errormsg){
		$(".emperrormsg").html(errormsg);
	}
	
	function displayError(errormsg){
		$(".errormsg").html(errormsg);
	}
	
	function saveEstablishment(button){
		var parent = button.parent().parent();
		var establishment = {
			name: parent.find(".supplier").val(),
			taxIDNumber: parent.find(".tin").val(),
			address: parent.find(".address").val(),
			municipality: parent.find(".municipality").val()
		};
		
		$.ajax({
			url: 'ajax.jspx?action=addEstablishment&establishment=' + JSON.stringify(establishment),
			type: "post",
			contentType: "application/json",
			dataType: "json"
		});
	}
	
	function saveReceipt(button){
		var parent = button.parent().parent();
		var receipt = {
				"owner" : {
					"employeeID": $(".employeeID").val(),
					"firstName" : $(".fname").val(),
					"lastName" : $(".lname").val(),
					"middleName" : $(".mname").val()
				},
				"establishment" : {
					"taxIDNumber" : parent.find(".tin").val(),
					"name" : parent.find(".supplier").val(),
					"address" : parent.find(".address").val(),
					"municipality" : parent.find(".municipality").val()
				},
				"grossPurchase" : parent.find(".grossPurchase").val()
		};
		
		$.ajax({
			url: 'ajax.jspx?action=addReceipt&receipt=' + JSON.stringify(receipt),
			type: "post",
			contentType: "application/json",
			dataType: "json"
		});
	}
	
	
	function exportToCSV(){
		$.ajax({
			url: 'ajax.jspx?action=receiptsToCsv',
			type: "get"
		});
	}
	
});
